package dao

import (
	"context"
	"encoding/json"
	"fmt"
	"strconv"
	"www.bwbdim.com/global"
	"www.bwbdim.com/internal/dto"
	"www.bwbdim.com/internal/model"
)

type UsersDao struct {
}

func NewUsersDao() *UsersDao {
	return &UsersDao{}
}

func (u *UsersDao) Login(req dto.LoginReq) (users model.Users, count int64, err error) {

	db := global.MySqlDB
	db = db.Select("id,username,nickname,active")
	db = db.Where("username = ? and password = ?", req.Username, req.Password)

	count = db.First(&users).RowsAffected

	err = db.Error

	return users, count, err
}

func (u *UsersDao) SetTokenToRedis(token string, userInfo model.Users) (int64, error) {

	userInfoJson, _ := json.Marshal(userInfo)

	fmt.Println(string(userInfoJson))

	usersFields := map[string]string{
		"token":    token,
		"userInfo": string(userInfoJson),
	}

	result, err := global.RDB.HSet(context.Background(), strconv.Itoa(userInfo.Id), usersFields).Result()
	if err != nil {
		return 0, err
	}

	return result, nil
}
